package com.wifi;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


public class OpenClientDemo {
    byte[] aesEncrypt(byte[] input, byte[] aesKey) {
        try {
            byte[] aesIv = {0x01, 0x01, 0x01, 0x1, 0x01, 0x01, 0x01, 0x1, 0x01, 0x01, 0x01, 0x1, 0x01, 0x01, 0x01, 0x1};
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
            return cipher.doFinal(input);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    byte[] getRsaPublicKey() {
        try {
            String key = "";

            BufferedReader br = new BufferedReader(new InputStreamReader(OpenClientDemo.class.getClassLoader().getResourceAsStream("publickey")));
//            BufferedReader br = new BufferedReader(new FileReader("publickey"));
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.startsWith("-")) {
                    key += line;
                }
            }
            br.close();

            return Base64.getDecoder().decode(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    byte[] rsaEncrypt(byte[] input, byte[] rsaPublicKey) {
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(rsaPublicKey);
            PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return cipher.doFinal(input);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    int postData(byte[] aesKeyEnc, byte[] jsonEnc) {
        try {
            String url = "http://test.openrcv.baidu.com/1017/agent.gif";
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeInt(0x484D3031);
            dos.writeInt(1);
            dos.writeInt(1017);
            dos.writeLong(0);
            dos.writeShort(2);
            dos.writeShort(1);
            dos.writeInt(0x484D3031);
            dos.writeInt(aesKeyEnc.length);
            dos.write(aesKeyEnc);
            dos.writeInt(jsonEnc.length);
            dos.write(jsonEnc);
            dos.flush();
            dos.close();
            return httpURLConnection.getResponseCode();
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    void run() {
        String aesKey = "0123456789abcdef";
        byte[] aesKeyEnc = rsaEncrypt(aesKey.getBytes(), getRsaPublicKey());
        if (aesKeyEnc == null) {
            return;
        }


        String json = "{\"payload\":[{\"domain\":\"xcastle.com\",\"dev_mac\":\"9C:50:EE:C6:21:E0\",\"usr_cap_time\":1441519201,\"usr_mac\":\"91:11:D1:01:91:31\",\"usr_distance\":5,\"longitude\": 123.0 , \"latitude\": 236.5, \"dev_ssid\":\"BaiduWifiTest1\"}]}";
        System.out.println("！！！！！注意！！！！！不要在payload中打包过多条抓取记录，加密后整个json的长度不能超过65535，否则会被截断。一般一次打包10条即可");
        //设备的抓取记录存在payload中，每次post的json body中只应包含一个payload。
        //在payload中可以同时打包多条数据， 格式为{"payload": [data1, data2, ...]}, 注意不是{"payload": [data1]}{"payload": [data2]}...。一个合法的例子如下
        //{"payload": [{"domain" : "baidu.com","dev_mac" : "11:22:33:AA:BB:CC","usr_cap_time" : 1441519201,"usr_mac": "68:a0:f6:7a:9a:4c","usr_distance": 10, "longitude": 123.2 , "latitude": 236.5, "dev_ssid":"BaiduWifiTest"}, {"domain" : "baidu.com","dev_mac" : "11:22:33:AA:BB:CC","usr_cap_time" : 1441519201,"usr_mac": "68:a0:f6:7a:9a:4f","usr_distance": 20, "longitude": 123.2 , "latitude": 236.5, "dev_ssid":"BaiduWifiTest"}]}
        // 字段解释#######################################################
        // domain: 使用账户注册时填写的域名
        // dev_mac: 抓取用户的AP设备MAC，需要绑定到具体门店，在绑定门店功能中创建并绑定门店
        // usr_cap_time: 抓取用户时间的unix时间戳，单位是秒
        // usr_mac: 抓取到的用户mac，AP抓到的所有mac地址不一定都是合法的用户mac，假mac会被过滤
        // usr_distance: 抓取时信号强度的相反数
        // longitude: AP设备的地理经度坐标
        // latitude: AP设备的地理纬度坐标
        // dev_ssid: AP设备接入的网络名称
        byte[] jsonEnc = aesEncrypt(json.getBytes(), aesKey.getBytes());
        if (jsonEnc == null) {
            return;
        }

        int code = postData(aesKeyEnc, jsonEnc);
        System.out.println("Return Code = " + code);
        
        System.out.println("200 OK只表示post请求已成功被服务器接收，但不代表符合业务统计要求，需要使用网页上的接口查询有数据才是真的成功");
        System.out.println("出现返回码100是不正常的。服务器不支持http的100 continue协议，libcurl或部分公开库可能默认开启此功能，需要关闭它");
    }



    public static void main(String[] args) {
        OpenClientDemo demo = new OpenClientDemo();
        demo.run();
    }
}

